package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.supervision.convert.JzdxReportReceiveConvert;
import com.engine4cloud.tdf.supervision.dto.create.JzdxAuditAcceptCreateDTO;
import com.engine4cloud.tdf.supervision.dto.create.JzdxAuditAssignCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxReportReceiveCaseQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxReportReceiveCaseResultDTO;
import com.engine4cloud.tdf.supervision.entity.JzdxReportReceiveCaseEntity;
import com.engine4cloud.tdf.supervision.mapper.JzdxReportReceiveCaseMapper;
import com.engine4cloud.tdf.supervision.service.JzdxReportReceiveCaseService;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * 矫正对象报到接收情况
 *
 * @author wenjie
 * @date 2024-04-18 09:22:20
 */
@Service
public class JzdxReportReceiveCaseServiceImpl extends ServiceImpl<JzdxReportReceiveCaseMapper, JzdxReportReceiveCaseEntity> implements JzdxReportReceiveCaseService {
    @Override
    public Boolean updateByCode(JzdxAuditAcceptCreateDTO dto) {
        JzdxReportReceiveCaseResultDTO result = Optional.ofNullable(this.getByCode(dto.getRybh()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        return super.updateById(JzdxReportReceiveConvert.INSTANCE.update(dto, result.getId()));
    }

    @Override
    public Boolean saveOrUpdateByCode(JzdxAuditAssignCreateDTO dto, Long tenantId) {
        JzdxReportReceiveCaseResultDTO result = this.getByCode(dto.getRybh());
        if (Objects.isNull(result)) {
            return super.save(JzdxReportReceiveConvert.INSTANCE.create(dto, tenantId));
        }

        return super.updateById(JzdxReportReceiveConvert.INSTANCE.update(dto, result.getId()));
    }

    @Override
    public JzdxReportReceiveCaseResultDTO getByCode(String code) {
        return JzdxReportReceiveConvert.INSTANCE.convert(getOne(wrapperOne(new JzdxReportReceiveCaseQueryDTO(code))));
    }

    private LambdaQueryWrapper<JzdxReportReceiveCaseEntity> wrapperOne(JzdxReportReceiveCaseQueryDTO query) {
        LambdaQueryWrapper<JzdxReportReceiveCaseEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(JzdxReportReceiveCaseEntity::getId, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(JzdxReportReceiveCaseEntity::getRybh, v));
        wrapper.orderByDesc(JzdxReportReceiveCaseEntity::getCreateTime);
        wrapper.last("LIMIT 1");
        return wrapper;
    }

}